﻿using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;

namespace ParserGenerator.ScannerConstruction
{
    [Serializable]
    public sealed class ScannerAutomatonStatePredecessorsTable : ReadOnlyDictionary<ScannerAutomatonState, ScannerAutomatonStatePredecessors>
    {
        internal ScannerAutomatonStatePredecessorsTable(ScannerAutomatonStateTable states)
            : base(new Dictionary<ScannerAutomatonState, ScannerAutomatonStatePredecessors>())
        {
            if (states == null)
                throw new ArgumentNullException(nameof(states));
            foreach (ScannerAutomatonState state in states)
                foreach (var t in state.Transitions.Values)
                    this[t.Target].Add(state);
        }

        public new ScannerAutomatonStatePredecessors this[ScannerAutomatonState state]
        {
            get
            {
                if (state == null)
                    throw new ArgumentNullException(nameof(state));
                ScannerAutomatonStatePredecessors predecessors;
                if (!Dictionary.TryGetValue(state, out predecessors))
                {
                    predecessors = new ScannerAutomatonStatePredecessors();
                    Dictionary.Add(state, predecessors);
                }
                return predecessors;
            }
        }
    }
}
